package com.yan.core.factory;


import com.yan.core.annotations.Autowired;
import com.yan.core.annotations.Service;
import com.yan.core.annotations.parse.ParseAnnotation;
import com.yan.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 代理工厂类
 *
 * @Author: 汪焰
 * @Date: 2020/11/24 21:51
 */
@Service
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;

    /**
     * JDK 代理事务的方法
     *
     * @Author: 汪焰
     * @Date: 2020/11/24 21:58
     */
    public Object transactionJdk(Object o) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;
                        try {
                            System.out.println("JDK代理 事务类 ：" + ParseAnnotation.parseBeanName(o.getClass()) + "；事务方法:" + method.getName());
                            transactionManager.beginTransaction();
                            result = method.invoke(o, args);
                            transactionManager.commit();
                        } catch (Exception e) {
                            System.out.println("事务出现异常 进行回滚");
                            transactionManager.rollback();
                            throw new Exception(e);
                        }
                        return result;
                    }
                });
    }

    /**
     * CgLib 代理事务的方法
     *
     * @Author: 汪焰
     * @Date: 2020/11/24 21:58
     */
    public Object transactionCgLib(Object o) {
        System.out.println("-----------transactionCgLib--------"+o.getClass());
        return Enhancer.create(o.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                Object result = null;
                try {
                    System.out.println("Cglib 代理 事务类 ：" + ParseAnnotation.parseBeanName(o.getClass()) + "；事务方法:" + method.getName());
                    transactionManager.beginTransaction();
                    result = method.invoke(o, objects);
                    transactionManager.commit();
                } catch (Exception e) {
                    System.out.println("事务出现异常 进行回滚");
                    transactionManager.rollback();
                    throw new Exception(e);
                }
                return result;
            }
        });
    }

}
